/**
 * 此模块是用来进行用户登陆及登出的
 */
import { reqUserLogin, reqGetUserInfo, reqUserLogout } from '@/api/login';
const state = {
  token: localStorage.getItem('token_key'),
  userInfo: {},
};
const mutations = {
  SAVE_USERINFO(state, token) {
    state.token = token;
  },
  RECEIVE_USERINFO(state, userInfo) {
    state.userInfo = userInfo;
  },
  SAVE_DELUSERINFO(state) {
    state.userInfo = {};
    state.token = '';
  },
};
const actions = {
  //1.用户登录
  async userLogin({ commit }, user) {
    const result = await reqUserLogin(user);
    if (result.code === 200) {
      //保证第一次通过token拿到用户信息，如果不写的话，第一次登录完成，state里面没有保存token，那么我们就不能从state里面拿到token，然后通过token进行判断
      commit('SAVE_USERINFO', result.data.token);
      //将token保存到localStorage里面
      localStorage.setItem('token_key', result.data.token);
      return 'ok';
    } else {
      return Promise.reject(new Error('failed'));
    }
  },
  //2.根据token获取用户信息
  async getUserInfo({ commit }) {
    const result = await reqGetUserInfo();
    if (result.code === 200) {
      console.log(result);
      commit('RECEIVE_USERINFO', result.data);
      return 'ok';
    } else {
      return Promise.reject(new Error('failed'));
    }
  },
  //3.用户登出
  async UserLogout({ commit }) {
    const result = await reqUserLogout();
    if (result.code === 200) {
      // 为了方便起见，可以在本地存储localStorage里保留一份，这样刷新页面的时候，也可以直接访问
      localStorage.removeItem('token_key');
      commit('SAVE_DELUSERINFO');
      return 'ok';
    } else {
      return Promise.reject(new Error('failed'));
    }
  },
};
const getters = {};
export default {
  state,
  mutations,
  actions,
  getters,
};
